#include "smartdelegate.h"

SmartDelegate::SmartDelegate(QObject * parent)
     :QItemDelegate(parent)
{
    isDefaultPrecision = true;
    isDefaultAlign     = true;
    isReadOnly         = false;
    isPasswordHolder   = false;
    isLogicDelegate    = false;
}


void SmartDelegate::setAlign(Qt::Alignment align)
{
    this->align = align;
    isDefaultAlign = false;
}

void SmartDelegate::setPrecision(int precision)
{
    this->precision = precision;
    isDefaultPrecision = false;
}

void SmartDelegate::setReadOnly()
{
    this->isReadOnly = true;
}

void SmartDelegate::setPasswordHolder()
{
    this->isPasswordHolder = true;
}

void SmartDelegate::setLogicDelegate()
{
    this->isLogicDelegate = true;
}


void SmartDelegate::drawDisplay ( QPainter * painter, const QStyleOptionViewItem & option, const QRect & rect, const QString & text ) const
{
    QStyleOptionViewItem opt = option;
    bool ok;
    double value = text.toDouble(&ok);

    if(!isDefaultAlign)
     opt.displayAlignment = align;
    else
     if(ok) // default numerics aligned right
       opt.displayAlignment |= Qt::AlignRight;

    QString txt;
    if(!isDefaultPrecision&&ok)
        if(precision>=0)
          txt = QString::number(value,'f', precision);
        else
          txt = QString::number(value);
    else
        txt = text;

    if(isLogicDelegate){
        if(value>0)
            QItemDelegate::drawDisplay ( painter, opt, rect, "Да");
           // QItemDelegate::drawCheck(painter, opt, rect, Qt::Checked);
        else
            QItemDelegate::drawDisplay ( painter, opt, rect, "Нет");
           // QItemDelegate::drawCheck(painter, opt, rect, Qt::Unchecked);
        return;
    }

    QItemDelegate::drawDisplay ( painter, opt, rect, txt);
}

QWidget *SmartDelegate::createEditor ( QWidget *wg, const QStyleOptionViewItem &sovi,
                                 const QModelIndex &mi) const
{
    if(isReadOnly)
      return 0;
    else
      return QItemDelegate::createEditor (wg, sovi, mi);
}
